package org.krivtsun.jpref;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.*;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: kontiky
 * Date: 25.03.2007
 * Time: 0:17:39
 * To change this template use File | Settings | File Templates.
 */
public class HumanGamer extends Gamer {

    private Map<Suit, Set<Rank>> cardMap = new HashMap<Suit, Set<Rank>>();

//    HumanGamer() {
//        int width = BORDER + ImageProvider.getCardWidth() / 4 * 9 + ImageProvider.getCardWidth() + BORDER;
//        Dimension dim = new Dimension(width, BORDER + ImageProvider.getCardHeight() + BORDER);
//        setMinimumSize(dim);
//        setPreferredSize(dim);
//    }

    public void addCard(Card card) {
        Set<Rank> set = cardMap.get(card.getSuit());
        if (set == null) {
            set = new TreeSet<Rank>();
            cardMap.put(card.getSuit(), set);
        }
        set.add(card.getRank());
    }

    protected BufferedImage getCardImage(Card card) {
        return ImageProvider.getCardImage(card);
    }

    @Override
    public Dimension getPreferredSize() {
        int width = 0;
        int i = 0;
        for (Suit s : Suit.values()) {
            Set<Rank> set = cardMap.get(s);
            if (set != null) {
                width += (set.size() - 1) * (ImageProvider.getCardWidth() / 4) + ImageProvider.getCardWidth();
                i++;
            }
        }
        width += i * ImageProvider.getCardWidth() / 4;
        return new Dimension(width, BORDER + ImageProvider.getCardHeight() + BORDER);
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        int x = (getWidth() - getPreferredSize().width) / 2;
        for (Suit s : Suit.values()) {
            Set<Rank> rankSet = cardMap.get(s);
            if (rankSet != null) {
                List<Rank> rankList = new ArrayList<Rank>(rankSet);
                Collections.sort(rankList, new Comparator<Rank>() {
                    public int compare(Rank o1, Rank o2) {
                        return -o1.compareTo(o2);
                    }
                });
                for (Rank r : rankList) {
                    drawCard(getCardImage(new Card(r, s)), g, x, BORDER);
                    x += ImageProvider.getCardWidth() / 4;
                }
                x += ImageProvider.getCardWidth();
            }
        }
    }
}
